package org.sauceggplant;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;

import java.io.*;
import java.security.*;

public class PemUtil {

    public static final String ALGORITHM = "RSA";

    public static final int KEY_SIZE = 2048;

    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        return keyPairGenerator.generateKeyPair();
    }

    public static void writePem(KeyPair keyPair) {
        try {
            FileWriter fileWriter = new FileWriter("key/PrivateKey.pem");
            PemWriter pemWriter = new PemWriter(fileWriter);
            PrivateKey privateKey = keyPair.getPrivate();
            pemWriter.writeObject(new PemObject("RSA PRIVATE KEY", privateKey.getEncoded()));
            pemWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            FileWriter fileWriter = new FileWriter("key/PublicKey.pem");
            PemWriter pemWriter = new PemWriter(fileWriter);
            PublicKey publicKey = keyPair.getPublic();
            pemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
            pemWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] readPem(File pemFile) {
        try {
            FileReader fileReader = new FileReader(pemFile);
            PemReader pemReader = new PemReader(fileReader);
            PemObject pemObject = pemReader.readPemObject();
            return pemObject.getContent();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        PemUtil.writePem(PemUtil.generateKeyPair());
    }
}
